using System;
using System.IO;
using System.Net;
using System.Xml.Serialization;

namespace VlcPlayer
{
	public class VlcAccess
	{
		public delegate void BrowseFileCallback(bool success);
		public event EventHandler AsyncRequestStarted;
        public event EventHandler AsyncRequestCompleted;
		public event BrowseFileCallback OnBrowseFileCompleted;
		public BrowseInfo BrowseInfo{get;set;}

        private string _host;

        public VlcAccess(string host)
        {
            _host = host;
        }

		public void SendChangeDirCommand(string dirPath)
		{
			string text = string.Format("http://{0}/requests/browse.xml?dir={1}", _host, dirPath);
			WebRequest webRequest = WebRequest.Create(text);
			webRequest.BeginGetResponse(new AsyncCallback(BrowseResponseCallback), webRequest);
			RaiseAsyncRequestStartedEvent();
		}
		private void BrowseResponseCallback(IAsyncResult result)
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
			try
			{
				HttpWebResponse httpWebResponse = httpWebRequest.EndGetResponse(result) as HttpWebResponse;
				if (httpWebResponse.StatusCode == HttpStatusCode.OK)
				{
					using (Stream responseStream = httpWebResponse.GetResponseStream())
					{
						using (StreamReader streamReader = new StreamReader(responseStream))
						{
							XmlSerializer xmlSerializer = new XmlSerializer(typeof(BrowseInfo));
							BrowseInfo = (xmlSerializer.Deserialize(streamReader) as BrowseInfo);
						    var ms = new MemoryStream();
						    var sr = new StreamWriter(ms);
                            xmlSerializer.Serialize(sr, new BrowseInfo(){Elements = new element[]{new element()}});
						    ms.Position = 0;
						    var sr2 = new StreamReader(ms);
						    var s=sr2.ReadToEnd();
							OnBrowseFileCompleted(true);
						}
					}
				}
			}
			catch (Exception ex)
			{
                if (httpWebRequest.RequestUri.AbsoluteUri.EndsWith("="))
                {
                    //try linux
                    SendChangeDirCommand("/");
                }
                else
                {
                    OnBrowseFileCompleted(false);
                }
			}
			finally
			{
				RaiseAsyncRequestCompletedEvent();
			}
		}
		private void RaiseAsyncRequestStartedEvent()
		{
			if (AsyncRequestStarted != null)
			{
				AsyncRequestStarted(this, new EventArgs());
			}
		}
		private void RaiseAsyncRequestCompletedEvent()
		{
			if (AsyncRequestCompleted != null)
			{
				AsyncRequestCompleted(this, new EventArgs());
			}
		}
	}
}
